<template>
  <div class="my-bidding-container">
    <div class="content">
      <el-card shadow="never" class="bidding-card">
        <div class="table-header">
          <h3>我的投标项目</h3>
          <div class="search-box">
            <el-input
              placeholder="请输入标的名称搜索"
              v-model="searchQuery"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
              class="search-input"
            >
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
        </div>

        <el-table
          :data="pagedData"
          style="width: 100%"
          v-loading="loading"
          stripe
          border
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column
            prop="id"
            label="序号"
            width="80"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="name"
            label="标的发布名称"
            min-width="220"
            header-align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="endTime"
            label="投标结束时间"
            width="140"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="status"
            label="状态"
            width="120"
            align="center"
            header-align="center"
          >
            <template #default="{ row }">
              <el-tag :type="statusMap[row.status].type" effect="light">
                {{ statusMap[row.status].text }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="180"
            align="center"
            header-align="center"
            fixed="right"
          >
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'registered'"
                type="primary"
                size="small"
                @click="handleSubmitMaterials(row)"
                plain
              >
                提交资料
              </el-button>
              <el-button
                v-else-if="row.status === 'pending'"
                type="info"
                size="small"
                disabled
              >
                等待报名
              </el-button>
              <el-button
                v-else
                type="success"
                size="small"
                @click="handleView(row)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="filteredData.length"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 提交资料对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`提交资料 - ${currentBid.name}`"
      width="50%"
    >
      <el-form label-width="120px">
        <el-form-item label="上传投标文件">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            multiple
            :limit="10"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :http-request="handleUpload"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持文件类型：pdf/zip/rar/png/jpeg等，单文件不超过100MB，最多可上传10个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMaterials">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 搜索相关
const searchQuery = ref('')
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const currentBid = ref({})
const fileList = ref([])

// 状态映射
const statusMap = {
  registered: { text: '报名成功', type: 'success' },
  pending: { text: '待开标', type: 'warning' },
  reviewing: { text: '资质审核', type: 'info' },
  result: { text: '开标结果', type: '' },
  expired: { text: '已过期', type: 'danger' },
  won: { text: '已中标', type: 'success' },
  lost: { text: '未中标', type: 'danger' }
}

// 投标项目数据
const bidList = ref([
  {
    id: '01',
    name: '四川省交通建设集团有限责任公司智能化场招标采购的公示',
    endTime: '2022-04-13',
    status: 'registered'
  },
  {
    id: '02',
    name: '校工会交互智能平板采购竞价成交公告',
    endTime: '2022-04-13',
    status: 'registered'
  },
  {
    id: '03',
    name: '平邑县图书馆馆藏图书及智能化设备采购项目中标结果公示',
    endTime: '2022-04-13',
    status: 'registered'
  },
  {
    id: '04',
    name: '三一智能电机-局部发电设备-招标招标公告',
    endTime: '2022-04-13',
    status: 'registered'
  },
  {
    id: '05',
    name: '中电鸿信息科技有限公司2023年警务室智能化改造项目单一来源采购方案公示',
    endTime: '2022-04-13',
    status: 'pending'
  },
  {
    id: '06',
    name: '海头镇宅基村土地发包项目',
    endTime: '2022-04-13',
    status: 'pending'
  },
  {
    id: '07',
    name: '先锋创业大楼（515-1室）60m²',
    endTime: '2022-04-13',
    status: 'pending'
  },
  {
    id: '08',
    name: '万达开绿色智能铸造产业园项目（二期）',
    endTime: '2022-04-13',
    status: 'reviewing'
  },
  {
    id: '09',
    name: '2023年度工伤基金结算支付智能审核监控项目竞争性磋商公告',
    endTime: '2022-04-13',
    status: 'pending'
  },
  {
    id: '10',
    name: '万达开绿色智能铸造产业园项目（三期）比选结果公告',
    endTime: '2022-04-13',
    status: 'result'
  },
  {
    id: '11',
    name: '太原市迎泽区卫生局卫生监督所2023年4月至12月政府采购意向-公用经费项目',
    endTime: '2022-04-13',
    status: 'expired'
  },
  {
    id: '12',
    name: '侯马市第二中学校2023年4月至11月政府采购意向-城乡义务教育补助经费中央资金',
    endTime: '2022-04-13',
    status: 'expired'
  }
])

// 计算属性
const filteredData = computed(() => {
  if (!searchQuery.value) return bidList.value
  const query = searchQuery.value.toLowerCase()
  return bidList.value.filter(item => 
    item.name.toLowerCase().includes(query) ||
    item.id.toLowerCase().includes(query))
})

const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const handlePageChange = (val) => {
  currentPage.value = val
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const loadData = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    total.value = filteredData.value.length
    loading.value = false
  }, 500)
}

const handleSubmitMaterials = (row) => {
  currentBid.value = row
  dialogVisible.value = true
}

const handleView = (row) => {
  router.push(`/bidding/detail/${row.id}`)
}

const beforeUpload = (file) => {
  const validTypes = ['application/pdf', 'application/zip', 'application/x-rar-compressed', 'image/png', 'image/jpeg']
  const isLt100M = file.size / 1024 / 1024 < 100
  
  if (!validTypes.includes(file.type)) {
    ElMessage.error('只能上传pdf/zip/rar/png/jpeg格式的文件!')
    return false
  }
  if (!isLt100M) {
    ElMessage.error('单个文件大小不能超过100MB!')
    return false
  }
  return true
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传10个文件')
}

const handleUpload = (file) => {
  // 实际项目中这里应该是上传到服务器的逻辑
  fileList.value.push(file)
}

const submitMaterials = () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请至少上传一个文件')
    return
  }
  
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    ElMessage.success('资料提交成功')
    currentBid.value.status = 'pending'
    dialogVisible.value = false
    fileList.value = []
    loading.value = false
  }, 1000)
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.my-bidding-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);

  .content {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

    .bidding-card {
      border: none;
    }

    .breadcrumb {
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      flex-wrap: wrap;
      gap: 15px;

      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }

      .search-box {
        width: 350px;

        .search-input {
          :deep(.el-input-group__append) {
            background-color: var(--el-color-primary);
            color: white;
            border-color: var(--el-color-primary);

            .el-button {
              color: white;
            }
          }
        }
      }
    }

    .pagination {
      margin-top: 25px;
      display: flex;
      justify-content: flex-end;
    }

    .el-table {
      margin-top: 15px;
      --el-table-border-color: var(--el-border-color-light);
      --el-table-header-bg-color: #f5f7fa;
      --el-table-row-hover-bg-color: #f5f7fa;

      :deep(.el-table__cell) {
        padding: 12px 0;
      }
    }
  }
}

@media (max-width: 768px) {
  .my-bidding-container {
    padding: 10px;

    .content {
      padding: 15px;

      .table-header {
        flex-direction: column;
        align-items: flex-start;

        .search-box {
          width: 100%;
          margin-top: 10px;
        }
      }
    }
  }
}
</style>